package de.mfits.fireflyplayer;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import de.mfits.fireflyplayer.service.PlaybackService;

public class PlaybackActivity extends Activity {
  public static final String ACTION = "de.mfits.fireflyplayer.PLAYBACK";

  private PlaybackService service;
  private SeekBar seekBar;

  Handler handler = new Handler();

  private ImageButton pauseButton;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.playback);

    service = PlaybackService.bindClient(this);

    seekBar = (SeekBar) findViewById(android.R.id.progress);
    pauseButton = (ImageButton) findViewById(R.id.pause);
    pauseButton.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        try {
          if (service.isPlaying()) {
            service.pause();
          } else {
            service.start();
          }
        } catch (RemoteException e) {
          Log.e(getClass().getSimpleName(), e.getMessage(), e);
        }
      }
    });

    seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

      @Override
      public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {
        try {
          if (fromTouch) {
            service.seekTo(progress);
          }
        } catch (RemoteException e) {
          Log.e(getClass().getSimpleName(), e.getMessage(), e);
        }
      }

      @Override
      public void onStartTrackingTouch(SeekBar seekBar) {
      }

      @Override
      public void onStopTrackingTouch(SeekBar seekBar) {
      }
    });

    new Timer().schedule(new TimerTask() {
      @Override
      public void run() {
        handler.post(new Runnable() {
          @Override
          public void run() {
            updateDisplay();
          }
        });
      }
    }, 0, 1000);
  }

  private void updateDisplay() {
    try {
      seekBar.setMax(service.getDuration());
      seekBar.setProgress(service.getCurrentPosition());
      updatePauseButton(service.isPlaying());

    } catch (RemoteException e) {
      Log.e(getClass().getSimpleName(), e.getMessage(), e);
    }
  }

  private void updatePauseButton(boolean playing) {
    pauseButton.setImageResource(playing ? android.R.drawable.ic_media_pause
        : android.R.drawable.ic_media_play);
  }
}
